<template>
    <div id="body">
      <h1>教务管理系统</h1>
      <el-form :rules="rules"
               v-loading="loading"
               element-loading-text="正在登录..."
               element-loading-spinner="el-icon-loading"
               element-loading-background="rgba(0, 0, 0, 0.8)"
               ref="loginForm"
               :model="loginForm"
               class="loginContainer">
        <el-form-item prop="account">
          <el-input type="text" auto-complete="false" v-model="loginForm.account"
                    placeholder="请输入账户"></el-input>
        </el-form-item>
        <el-form-item prop="password">
          <el-input type="password" auto-complete="false" v-model="loginForm.password"
                    placeholder="请输入密码"></el-input>
        </el-form-item>
        <el-form-item>
          <el-select v-model="loginForm.roleId" placeholder="请选择">
            <el-option
                v-for="item in roles"
                :key="item.id"
                :label="item.roleName"
                :value="item.id">
            </el-option>
          </el-select>
        </el-form-item>
        <el-button type="primary" style="width: 100%" @click="submitLogin">登录</el-button>
      </el-form>
    </div>
</template>

<script>

export default {
  name: "Login",
  data(){
    return {
      loginForm: {
        account: '123456',
        password: '123456',
        roleId: 1
      },
      roles:[],
      loading: true,
      rules: {
        account: [{required: true, message: '请输入账号', trigger: 'blur'}],
        password: [{required: true, message: '请输入密码', trigger: 'blur'}],
      }
    }
  },
  methods:{
    submitLogin() {
      this.$refs.loginForm.validate((valid) => {
        if (valid) {
          this.loading=true;
          this.postRequest('/login', this.loginForm).then(resp => {
            this.loading = false;
            if (resp.status===200) {
              sessionStorage.setItem("user",JSON.stringify(resp.data));
              this.$router.push(resp.data.page)
            }
          })
        } else {
          this.$message.error('请输入所有字段！');
          return false;
        }
      });
    }
  },
  created() {
    this.getRequest('/getRoles').then(resp => {
      this.roles = resp.data
    })
    this.loading = false
  }
}
</script>
<style scoped>
#body{
  width: 30%;
  margin: 180px auto auto;
}
</style>
